import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class FocusScopeManager extends StatefulWidget {
  final FocusScopeNode focusScopeNode;
  final Widget child;
  final bool? autofocus;
  final void Function(LogicalKeyboardKey key)? onDirectKeyDown;
  final FocusOnKeyEventCallback? onKeyEvent;

  FocusScopeManager(
      {super.key,
      FocusScopeNode? focusScopeNode,
      required this.child,
      this.autofocus,
      this.onKeyEvent,
      this.onDirectKeyDown})
      : focusScopeNode = focusScopeNode ?? FocusScopeNode();

  @override
  State<FocusScopeManager> createState() => _FocusScopeManagerState();
}

class _FocusScopeManagerState extends State<FocusScopeManager> {
  @override
  Widget build(BuildContext context) {
    return FocusScope(
      node: widget.focusScopeNode,
      autofocus: widget.autofocus ?? false,
      child: widget.child,
      onKeyEvent: (node, event) {
        KeyEventResult result = KeyEventResult.ignored;
        if (event is KeyDownEvent) {
          switch (event.logicalKey) {
            case LogicalKeyboardKey.arrowUp:
              widget.onDirectKeyDown?.call(event.logicalKey);
              widget.focusScopeNode.focusInDirection(TraversalDirection.up);
              result = KeyEventResult.handled;
              break;
            case LogicalKeyboardKey.arrowDown:
              widget.onDirectKeyDown?.call(event.logicalKey);
              widget.focusScopeNode.focusInDirection(TraversalDirection.down);
              result = KeyEventResult.handled;
              break;
            case LogicalKeyboardKey.arrowLeft:
              widget.onDirectKeyDown?.call(event.logicalKey);
              widget.focusScopeNode.previousFocus();
              result = KeyEventResult.handled;
              break;
            case LogicalKeyboardKey.arrowRight:
              widget.onDirectKeyDown?.call(event.logicalKey);
              widget.focusScopeNode.nextFocus();
              result = KeyEventResult.handled;
              break;
          }
        }
        return widget.onKeyEvent?.call(node, event) ?? result;
      },
    );
  }
}
